package cn.cxyxj.code_auth_jwt_persistence_prod.auth.handler;


import cn.cxyxj.code_auth_jwt_persistence_prod.common.ApiResult;
import cn.cxyxj.code_auth_jwt_persistence_prod.common.RedisKey;
import cn.cxyxj.code_auth_jwt_persistence_prod.entity.SysUser;
import cn.cxyxj.code_auth_jwt_persistence_prod.entity.SysUserDetails;
import cn.cxyxj.code_auth_jwt_persistence_prod.utils.JwtUtil;
import cn.cxyxj.code_auth_jwt_persistence_prod.utils.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;

/**
 * 登录成功回调
 */
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    boolean ONE_LOGIN = true;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 登录成功，返回json格式
        SysUserDetails principal = (SysUserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        SysUser sysUser = principal.getSysUser();
        String token = JwtUtil.createToken(username);
        // 如下逻辑为：同账号多次登录，只存储最后一次登录产生的token。即同账号同时只能一人处于登录状态
        if(ONE_LOGIN){
            // key:user-token:dev
            String oldTokenStr = RedisUtil.get(String.format(RedisKey.USER_TOKEN, sysUser.getAccount()));
            // 获取老token，将老token删除
            if (StringUtils.hasLength(oldTokenStr)) {
                RedisUtil.del(String.format(RedisKey.TOKEN, oldTokenStr));
            }
            // 保存到 Redis 中，并设置过期时间
            RedisUtil.set(String.format(RedisKey.USER_TOKEN, sysUser.getAccount()), token, Duration.ofDays(7));
            RedisUtil.set(String.format(RedisKey.TOKEN, token), JSONObject.toJSONString(principal), Duration.ofDays(7));
        }else {
            // 允许多端同时登录，产生多个 Token

        }


        // 将用户的 token 放到 Cookie 中
        Cookie cookie = new Cookie("sso_user_token", token);
        response.addCookie(cookie);
        response.getWriter().println(JSONObject.toJSONString(ApiResult.success(token)));
        response.getWriter().flush();
        response.getWriter().close();
    }

}
